import os
import subprocess
import json
import hashlib
import sqlite3
from config import (
    FFPROBE_PATH, FFMPEG_PATH, MIN_VIDEO_DURATION, MID_VIDEO_DURATION,
    PREVIEW_SAVE_DIR, PREVIEW_WIDTH, PREVIEW_HEIGHT, PREVIEW_DURATION,
    GIF_FPS, GIF_QUALITY, DATABASE_PATH
)
from database import save_records

def get_video_duration(video_path):
    """使用ffprobe获取视频时长（秒）"""
    cmd = [
        FFPROBE_PATH,
        "-v", "error",
        "-show_entries", "format=duration",
        "-of", "json",
        video_path
    ]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        data = json.loads(result.stdout)
        return float(data["format"]["duration"])
    except Exception as e:
        print(f"获取时长失败 {video_path}: {str(e)}")
        return 0

def create_preview(video_path, preview_path, start_time):
    """生成单段预览GIF"""
    cmd = [
        FFMPEG_PATH,
        "-ss", str(start_time),          # 起始时间
        "-i", video_path,                # 输入文件
        "-t", str(PREVIEW_DURATION),     # 截取时长
        "-vf", f"scale={PREVIEW_WIDTH}:{PREVIEW_HEIGHT},fps={GIF_FPS}",  # 压缩分辨率和帧率
        "-y",                            # 覆盖已存在文件
        preview_path
    ]
    subprocess.run(cmd, capture_output=True, check=True)

def merge_previews(temp_files, merged_path):
    """合并多个预览片段为单个GIF"""
    # 生成临时文件列表
    list_file = os.path.normpath(os.path.join(os.path.dirname(merged_path), "temp_list.txt"))
    with open(list_file, "w", encoding='utf-8') as f:
        for file in temp_files:
            f.write(f"file '{os.path.normpath(file)}'\n")
    
    # 合并命令
    cmd = [
        FFMPEG_PATH,
        "-f", "concat",
        "-safe", "0",
        "-i", list_file,
        "-vf", f"scale={PREVIEW_WIDTH}:{PREVIEW_HEIGHT},fps={GIF_FPS}",
        "-y",
        merged_path
    ]
    subprocess.run(cmd, capture_output=True, check=True)
    
    # 清理临时文件
    for file in temp_files:
        os.remove(file)
    os.remove(list_file)

def get_unique_prefix(video_path):
    """根据视频绝对路径生成唯一md5前缀"""
    abs_path = os.path.abspath(video_path)
    md5 = hashlib.md5(abs_path.encode('utf-8')).hexdigest()
    return md5

def process_video(video_path):
    """处理单个视频文件主逻辑"""
    duration = get_video_duration(video_path)
    if duration < MIN_VIDEO_DURATION:
        return None  # 不处理短于30秒的视频

    # 创建预览目录（如果不存在）
    os.makedirs(PREVIEW_SAVE_DIR, exist_ok=True)
    
    # 生成唯一预览文件名前缀
    unique_prefix = get_unique_prefix(video_path)
    preview_files = []

    try:
        if duration <= MID_VIDEO_DURATION:  # 30秒~5分钟
            start_time = max(0, duration/2 - PREVIEW_DURATION/2)  # 取中间3秒
            preview_path = os.path.join(PREVIEW_SAVE_DIR, f"{unique_prefix}_mid.gif")
            create_preview(video_path, preview_path, start_time)
            preview_files.append(preview_path)
        else:  # 大于5分钟
            temp_files = []
            for idx, ratio in enumerate([1/3, 1/2, 2/3]):  # 三个时间点
                start = max(0, duration * ratio - PREVIEW_DURATION/2)
                temp_path = os.path.join(PREVIEW_SAVE_DIR, f"{unique_prefix}_temp_{idx+1}.gif")
                create_preview(video_path, temp_path, start)
                temp_files.append(temp_path)
            
            # 合并生成最终预览
            merged_path = os.path.join(PREVIEW_SAVE_DIR, f"{unique_prefix}_long.gif")
            merge_previews(temp_files, merged_path)
            preview_files.append(merged_path)

        # 保存到数据库
        save_records(video_path, preview_files, duration)

        return preview_files
    except Exception as e:
        print(f"处理失败 {video_path}: {str(e)}")
        return None
    